package com.kgc.scd.controller;

import com.kgc.scd.constant.CommonConstant;
import com.kgc.scd.service.GoodsFeignService;
import com.kgc.scd.service.HistoryFeignService;
import com.kgc.scd.service.HotWordsFeignService;
import com.kgc.scd.util.*;
import com.kgc.scd.vo.SensitiveWord;
import com.kgc.scd.vo.ShopGoodsVO;
import com.kgc.scd.vo.ShopHistoryWordsVO;
import com.kgc.scd.vo.ShopHotWordsVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


@RestController
@Slf4j
@Api(tags = "05、首页搜索(hx)",value = "可以通过模糊匹配的方式查询到商品的详情")
public class GoodsController {

    @Autowired
    private SnowUtil snowUtil;
    //调用redis工具类
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private GoodsFeignService goodsFeignService;
    @Autowired
    private HistoryFeignService historyFeignService;

    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;
    @Autowired
    private HotWordsFeignService hotWordsFeignService;
    /**
     * 首页搜索
     * @param pageNo
     * @param pageSize
     * @param words
     * @return
     */
    @GetMapping("/goodsSearch")
    @ApiOperation(value = "1.首页搜索",notes = "搜索商品详情内容，模糊匹配")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo",value= "页码", required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页个数", required = true),
            @ApiImplicitParam(name = "words",value = "关键字", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 999,message = "失败")
    })
    public RequestResult<PageSupport<ShopGoodsVO>> GoodsList(@RequestParam(name = "pageNo", required = false, defaultValue = CommonConstant.DEFAULT_INIT_PAGE_NO) Integer pageNo,
                                      @RequestParam(name = "pageSize", required = false, defaultValue =CommonConstant.DEFAULT_INIT_PAGE_SIZE) Integer pageSize,
                                      @RequestParam(name = "words") String words){

        //敏感字列表
        List<SensitiveWord> listword=goodsFeignService.getSensitiveWords();
        List<String>stringList=listword.stream().map(SensitiveWord::getWord).collect(Collectors.toList());
        log.info("{}",stringList);

       if(stringList.contains(words)){
           return ResultBuildUtil.fail("999","当前为敏感字，请重新输入！！！");
       }

       //TODO 查询搜索内容
       PageSupport<ShopGoodsVO> shopGoodsVOList=goodsFeignService.GoodsList(pageNo, pageSize, words);
        //判断输入关键词后，查询不到内容，就是商品数量较少
        if(shopGoodsVOList.getTotalCount() == 0){
            return ResultBuildUtil.fail("999","您要的商品查找不到，可以看看其它商品！！！");
        }
        log.info("{}",shopGoodsVOList);


      return   ResultBuildUtil.success(shopGoodsVOList);
    }

    /**
     * 热词展示
     * @param words
     * @return
     */
    @GetMapping("/hotWords")
    @ApiOperation(value = "2.热词展示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "words",value = "关键字", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 999,message = "失败")
    })
    public RequestResult<?> GoodswordHot(@RequestParam(name = "words") String words){
        //TODO 热词展示
        //score大的排序前面，从第一个到第五个，取前五
        Set<Object>ld=redisUtils.revRange("words",0,5);
        log.info("集合：{}",ld);

        //获取集合中所有数值
        Set<Object>lds=redisUtils.rangeZset("words",0,-1);
        log.info("{}",lds);
        // 存储输入词到redis,使用 Sorted Set 实现。
        //设置一个分数如果存在，就score加一,相当于热度加一
        Double score=1.0;
        //判断该zset表是否存在该值,如果存在score加1，类似于热度加一,不存在就存入set
        if(lds.contains(words)){
            redisUtils.addScore("words",words,score);
        }else{
            List<ShopHotWordsVO>list=hotWordsFeignService.getlist();
            log.info("{}",list);
            List<String >list1=list.stream().map(ShopHotWordsVO::getWords).collect(Collectors.toList());
            if(list1.contains(words)) {
                redisUtils.addZset("words", words, score);
            }
        }
        return   ResultBuildUtil.success(ld);
    }

//    /**
//     * 查询历史搜索记录列表，以时间排序
//     * @return
//     */
//    @GetMapping("/historyWordlist")
//    @ApiOperation(value = "5.0.0历史搜索记录(数据库版本)")
//    @ApiResponses({
//            @ApiResponse(code = 200,message = "成功"),
//            @ApiResponse(code = 999,message = "失败")
//    })
//    public RequestResult<?> historyWord(){
//        List<ShopHistoryWordsVO>list=historyFeignService.getHistoryWords();
//        log.info("list:{}",list);
//        //事件关键词列表
//        List<String>lsitwords=list.stream().map(ShopHistoryWordsVO::getWords).collect(Collectors.toList());
//        List<String > list2 = lsitwords.stream().distinct().collect(Collectors.toList());
//        log.info("lsitwords去重{}",list2);
//        int count =list2.size();
//            log.info("数量：{}",count);
//        if(count>=10){
//            List<String>list3=new ArrayList<>();
//            list3.add(list2.get(9));
//            log.info("最久的值：{}",list3);
//            historyFeignService.delete(list3);
//        }
//
//       return ResultBuildUtil.success(list2);
//    }
//
//    /**
//     * 插入历史搜索记录
//     * @param words
//     * @return
//     */
//    @PostMapping("/historyWordadd")
//    @ApiOperation(value = "5.0.1历史搜索记录插入数据库(数据库版本)")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "words",value = "关键字", required = true)
//    })
//    @ApiResponses({
//            @ApiResponse(code = 200,message = "成功"),
//            @ApiResponse(code = 999,message = "失败")
//    })
//    public RequestResult<?> historyWordadd(@RequestParam(name = "words") String words){
//        List<ShopHistoryWordsVO>list=historyFeignService.getHistoryWords();
//        List<String >list1=list.stream().map(ShopHistoryWordsVO::getWords).distinct().collect(Collectors.toList());
//        //TODO 历史搜素记录存储数据库
//        ShopHistoryWordsVO shopHistoryWordsVO=new ShopHistoryWordsVO();
//        shopHistoryWordsVO.setId(snowUtil.snowId());
//        shopHistoryWordsVO.setWords(words);
//        shopHistoryWordsVO.setTime(new Date());
//        historyFeignService.intsert(shopHistoryWordsVO);
//        return ResultBuildUtil.success("历史记录存储成功");
//    }
//
//
//    /**
//     * 删除历史搜索记录
//     * @return
//     */
//    @GetMapping("/historyWordDelete")
//    @ApiOperation(value = "5.0.2历史搜索记录删除(数据库版本)")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "words",value = "关键词", required = true)
//    })
//    @ApiResponses({
//            @ApiResponse(code = 200,message = "成功"),
//            @ApiResponse(code = 999,message = "失败")
//    })
//    public RequestResult<?> historyWorddelete(@RequestParam List<String> words){
//        historyFeignService.delete(words);
//        return ResultBuildUtil.success("删除成功");
//    }




    /**
     * 历史记录查看
     * @param words
     * @return
     */
    @GetMapping("/historyWordsList")
    @ApiOperation(value = "3.搜索历史记录",notes = "搜索历史记录，有上限设置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "words",value = "关键字", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 999,message = "失败")
    })
    public RequestResult<?> Historyword(@RequestParam(name = "words") String words){

        //获取全部的值
        List<Object>ld=redisUtils.lGet("history",0,-1);
        log.info("{}",ld);
        //倒序
        Collections.reverse(ld);
        //获取数量
        int count=ld.size();
        log.info("{}",count);
        //判断是否存在
        if(ld.contains(words)){
            redisUtils.lRemove("history",1,words);
            redisUtils.lSet("history",words);
        }else{
            //判断数量是否超过十个，超过自动删除最久的一个值
            if(count>=5){
                List<Object>ls=redisUtils.lGet("history",0,-1);
                log.info("ls：{}",ls);
                log.info("{}",ld.get(0));
                redisUtils.lRemove("history",1,ls.get(0));
                redisUtils.lSet("history",words);
            }else {
                redisUtils.lSet("history",words);
            }
        }
        return   ResultBuildUtil.success(ld);
    }



    /**
     * 历史删除
     * @param words
     * @return
     */
    @GetMapping("/historyWordsDeleteR")
    @ApiOperation(value = "4.删除单个搜索历史记录",notes = "删除自己的搜索历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "words",value = "关键字", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 999,message = "失败")
    })
    public RequestResult<?> HistoryWordDelete( String words) {
        redisUtils.lRemove("history",1,words);

        return   ResultBuildUtil.success("删除成功");
    }
    /**
     * 历史删除
     * @param
     * @return
     */
    @GetMapping("/historyWordsDeleteAll")
    @ApiOperation(value = "5.清空历史记录",notes = "一键清空搜索历史记录")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 999,message = "失败")
    })
    public RequestResult<?> HistoryWordDeleteAll() {

            redisUtils.del("history");
        return   ResultBuildUtil.success("删除成功");
    }
}
